package ee.project.stack;

import ee.project.Overflow;
import ee.project.Underflow;

public class StackAr {

	public StackAr() {
		this(DEFAULT_CAPACITY);
	}

	public StackAr(int capacity) {
		theArray = new Object[capacity];
		topOfStack = -1;
	}

	public boolean isEmpty() {
		return topOfStack == -1;
	}

	public boolean isFull() {
		return topOfStack == theArray.length - 1;
	}

	public void makeEmpty() {
		topOfStack = -1;
	}

	public Object top() {
		if (isEmpty())
			return null;
		return theArray[topOfStack];
	}

	public void pop() throws Underflow {
		if (isEmpty())
			throw new Underflow();
		theArray[topOfStack--] = null;
	}

	public void push(Object x) throws Overflow {
		if (isFull())
			throw new Overflow();
		theArray[++topOfStack] = x;
	}

	public Object topAndPop() {
		if (isEmpty())
			return null;
		Object topItem = top();
		theArray[topOfStack--] = null;
		return topItem;
	}

	private Object[] theArray;
	private int topOfStack;

	static final int DEFAULT_CAPACITY = 10;

	public static void main(String[] args) {
		StackAr s = new StackAr(10001);

		try {
			for (int i = 0; i < 10000; i++)
				s.push(new Integer(i));
		} catch (Overflow e) {
			System.out.println("Unexpected overflow");
		}

		while (!s.isEmpty())
			System.out.println(s.topAndPop());
	}
}
